package com.dmgis.hndz.common.utils;


import com.dmgis.entity.ContourSetting;
import com.dmgis.entity.LongitudeLatitudeValue;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Objects;
import java.util.TimeZone;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@Service
public class TxtFileManager {

    @Value("${filePath.txtFilePath}")
    private String txtFile;
    @Autowired
    private ServletContext servletContext;

    /************************
     * @Description :
     * @param longitudeLatitudeValueList : 经纬度值
     * @param contourSettingList :等级参数和颜色
     * @return : java.lang.String
     ************************/

    public String getGridTxt(List<LongitudeLatitudeValue> longitudeLatitudeValueList, List<ContourSetting> contourSettingList){
        StringBuilder txt = new StringBuilder();
        // 添加基本参数
        txt.append("[基本参数]\n");
        //点的个数
        txt.append(longitudeLatitudeValueList.size()).append(",");
        //分级数
        txt.append(contourSettingList.size()).append(",");
        //服务名
        txt.append("yl,1,1.5,5,1,0,0,1\n");
        // 添加数据
        txt.append("[数据]\n");
        longitudeLatitudeValueList.forEach(longitudeLatitudeValue -> {
            txt.append(longitudeLatitudeValue.getLongitude()).append("\t")
                    .append(longitudeLatitudeValue.getLatitude()).append("\t")
                    .append(longitudeLatitudeValue.getValue()).append("\n");
        });
        // 添加分级参数
        txt.append("[分级参数]\n");
        contourSettingList.forEach(contourSetting -> {
            txt.append(contourSetting.getElementValue()).append(",")
                    .append(contourSetting.getElementColor()).append(",")
                    .append(contourSetting.getElementColor()).append(",")
                    .append("1,0,")
                    .append(contourSetting.getElementColor()).append(",")
                    .append("0,0,0,0").append("\n");
        });
        return txt.toString();
    }

    public String writeDataToTxtFile(String data, String fileName) throws IOException {
        // 确保文件名以".txt"结尾
        String formattedFileName = fileName.endsWith(".txt") ? fileName : fileName + ".txt";

        String tomcatPath = txtFile;
        // 构建文件路径
        Path filePath = Paths.get(tomcatPath, formattedFileName);
        // 将数据写入文件，如果文件已存在则覆盖内容
        Files.write(filePath, data.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + formattedFileName + "\"");
        headers.setContentType(MediaType.TEXT_PLAIN);
        headers.set(HttpHeaders.CONTENT_ENCODING, "UTF-8");

        FileSystemResource resource = new FileSystemResource(filePath.toFile());

        System.err.println(resource.getURL());

        return filePath.toString();
    }

    /************************
     * @Description :取出文件的文件夹路径
     * @param  filePath :文件路径
     * @return : java.lang.String
     ************************/

    public static String extractFolderPath(String filePath) {
        Path path = Paths.get(filePath);
        return path.getParent().toString();
    }

    public void scheduleFileDeletion() {
        Runnable task = () -> {
            deleteFilesInDirectory(txtFile);
        };

        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleAtFixedRate(task, 0, 1, TimeUnit.HOURS);
    }

    private void deleteFilesInDirectory(String directory) {
        try {
        Files.walkFileTree(Paths.get(directory), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    long hoursSinceCreation = LocalDateTime.now().until(
                            LocalDateTime.ofInstant(Files.getLastModifiedTime(file).toInstant(), TimeZone.getDefault().toZoneId()),
                            ChronoUnit.HOURS
                    );

                    if (hoursSinceCreation >= 1) {
                        Files.deleteIfExists(file);
                    }

                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /************************
     * @Description :在此文件夹下，如果文件时间超过maxAgeMillis，则删除文件
     * @param tempFolderPath:文件夹路径
     * @param maxAgeMillis:最大存在时间值
     * @return : void
     ************************/
    public static void cleanupTempFiles(String tempFolderPath, long maxAgeMillis) {
        File tempFolder = new File(tempFolderPath);

        long currentTimeMillis = System.currentTimeMillis();
        long thresholdTimeMillis = currentTimeMillis - maxAgeMillis;

        // 删除创建时间早于阈值时间的文件
        for (File file : Objects.requireNonNull(tempFolder.listFiles())) {
            if (file.lastModified() < thresholdTimeMillis) {
                try {
                    FileUtils.forceDelete(file);
                    System.out.println("Deleted: " + file.getName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


//    public static String urbanFireInsuranceToTxt(List<CshxZsyb> cshxZsybList, List<CshxSetting> cshxSettingList){
//        StringBuilder txt = new StringBuilder();
//        // 添加基本参数
//        txt.append("[基本参数]\n");
//        //点的个数
//        txt.append(cshxZsybList.size()).append(",");
//        //分级数
//        txt.append(cshxSettingList.size()).append(",");
//        //服务名
//        txt.append("yl,1,1.5,5,1,0,0,1\n");
//        // 添加数据
//        txt.append("[数据]\n");
//        cshxZsybList.forEach(cshxZsyb -> {
//            txt.append(cshxZsyb.getLon()).append("\t")
//                    .append(cshxZsyb.getLat()).append("\t")
//                    .append(cshxZsyb.getFireindex()).append("\n");
//        });
//        // 添加分级参数
//        txt.append("[分级参数]\n");
//        cshxSettingList.forEach(contourSetting -> {
//            txt.append(contourSetting.getValue()).append(",")
//                    .append(contourSetting.getColour()).append(",")
//                    .append(contourSetting.getColour()).append(",")
//                    .append("1,0,")
//                    .append(contourSetting.getColour()).append(",")
//                    .append("0,0,0,0").append("\n");
//        });
//        return txt.toString();
//    }
}